from selenium.webdriver.common.by import By
from utilities.CommonConfig import CommonConfig
from PIL import Image
import ddddocr
from utilities.ProjectUtil import ProjectUtil
from configobj import ConfigObj
class AutoLogin:
    def login(self,username,password):
        rootpath=ProjectUtil.project_root_path('agent-ui-auto-python')
        driver = CommonConfig.getChromeDriver()
        # (1)登录页面截图
        screenshotpath = rootpath+'outFiles/screenShot/pic.png'
        driver.save_screenshot(screenshotpath)  # 可以修改保存地址
        username = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div/form/div[1]/div/div[1]/input')
        username.clear()
        username.send_keys("username")
        password = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div/form/div[2]/div/div[1]/input')
        password.clear()
        password.send_keys("password")
        image = Image.open(screenshotpath)
        #验证码标签
        captchaurl = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div/form/div[3]/div/div[2]/img')
        left = captchaurl.location.get("x")#x点的坐标
        top = captchaurl.location.get("y")#y点的坐标
        right = left + captchaurl.size.get("width")#上面右边点的坐标
        bottom = top + captchaurl.size.get("height")#下面右边点的坐标
        # (4)将图片验证码截取
        cropimg = image.crop((left, top, right, bottom))
        cropimgpath=rootpath+'outFiles/screenShot/code.png'
        cropimg.save(cropimgpath)#截取的验证码图片保存为新的文件

        # cookie = webdriver.get_cookies()
        # print(cookie)
        with open(cropimgpath, 'rb') as f:
            content_captcha = f.read()
        # print(content_captcha)
        # 4.此处是重点，解析验证码，得到4位数字，只需要2行代码
        ocr = ddddocr.DdddOcr()
        code = ocr.classification(content_captcha)
        captcha = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div/form/div[3]/div/div[1]/input')

        captcha.clear()
        captcha.send_keys(code)

        submit = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div/form/div[4]/button')
        # driver.find_element_by_class_name("login-button ant-btn ant-btn-primary ant-btn-lg")
        submit.click()
        return driver


if __name__ == '__main__':
    autoLogin = AutoLogin()
    config = ConfigObj("../configs/agent_account.ini", encoding='UTF8')
    autoLogin.login(config['agent']['username'],config['agent']['password'])
